package it.polimi.travelDream.ejb.servlet;

import it.polimi.travelDream.ejb.interfaces.UserMgrRemote;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Map;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class TravelServlet
 */
@WebServlet("/UserRegistrationServlet")
public class UserRegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private final int DUPLICATE_DATA_ERROR = 1062;
	@EJB
	UserMgrRemote umr;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UserRegistrationServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		// TODO Auto-generated method stub
		System.out.println("sono in get");
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, String[]> mappa = request.getParameterMap();
		
		//empty fields
		if ( mappa.get("username")[0].isEmpty() || mappa.get("name")[0].isEmpty() || mappa.get("surname")[0].isEmpty() || mappa.get("mail")[0].isEmpty() || mappa.get("password")[0].isEmpty())
		{
			request.setAttribute("message","Empty fields");
			request.getRequestDispatcher("/Registration.jsp").forward(request, response);
		}
		
		//shortpwd
		else if (mappa.get("password").toString().length()<= 6)
		{
			request.setAttribute("message","Invalid Password");
			request.getRequestDispatcher("/Registration.jsp").forward(request, response);
		}
		
		//generic errors
		else 
		{
			try 
			{
				umr.create(mappa.get("username")[0], mappa.get("name")[0], mappa.get("surname")[0], mappa.get("mail")[0], mappa.get("password")[0]);
				request.setAttribute("message","User succesfully registered now please log in.");
				request.getRequestDispatcher("/login.jsp").forward(request, response);
			}
			catch (Exception e)
			{
			      	request.setAttribute("message","Duplicated user. Please try with different data.");
			      	request.getRequestDispatcher("/Registration.jsp").forward(request, response); 
			}
		}
	}
			
}
